<template>
  <div class="rt-x6-menu" :class="{ collapse: collapse }">
 
    <div class="rt-x6-menu-head" @click="onCollapse">
      <svg-icon icon-class="collapse"></svg-icon>
      <svg-icon :icon-class="language" class="lng" @click.stop="changeLanguage" v-show="!collapse"></svg-icon>
    </div>
    <div class="search" v-if="taskgroups.length>0&&!collapse">
        <input
            class="rt-input"
            v-model="keyword"
            @input="search"
            placeholder="请输入组件名称"
          />
      </div>
    <div class="group-contaner" v-if="taskgroups.length>0">
      <div v-for="(taskgroup, index) in taskgroups" :key="'taskgroup-' + index" class="group-page">
        <div class="taskgroup" @click="$set(taskgroup, 'taskgroupexpand', !taskgroup.taskgroupexpand)"  >
          <svg-icon icon-class="arrow-right" :class="{ expand:taskgroup.taskgroupexpand }"></svg-icon>
          {{ taskgroup.taskgrouptitle }}
        </div>
        <div v-for="(group, index) in groups" :key="index" v-show="taskgroup.taskgroupexpand">
          <div v-if="group.taskgroup === taskgroup.taskgroupname" class="group-page">
            <div class="group" @click="clickGroup(group)" :class="{ 'group-expand': group.expand }">
              <svg-icon icon-class="arrow-right" :class="{ expand: group.expand }"></svg-icon>
              {{ group.title }}
              <svg-icon class="loadingsvg" icon-class="loading" v-if="group.loadingGroups" ></svg-icon>
            </div>
            <div v-for="(node, index) in filteredNodes" :key="index" v-show="group.expand" @mousedown="start($event, node)">
              <div v-if="node.taskgroup === group.taskgroup" >
                <item :node="node" v-if="node.group === group.name&&group.taskgroup === taskgroup.taskgroupname"
                :text="language == 'zh-CN' ? node.data.node.displayName : node.data.node.displayNameEn"  />
              </div>
              
            </div>
          </div>
      </div>
      </div>
    </div>

    <div class="group-contaner" v-else>
      <div v-for="(group, index) in groups" :key="index" class="group-page">
        <div class="group" @click="$set(group, 'expand', !group.expand)" :class="{ 'group-expand': group.expand }">
          <svg-icon icon-class="arrow-right" :class="{ expand: group.expand }"></svg-icon>
          {{ group.title }}
        </div>
        <div v-for="(node, index) in nodes" :key="index" v-show="group.expand" @mousedown="start($event, node)">
          <item :node="node" v-if="node.group === group.name"
            :text="language == 'zh-CN' ? node.data.node.displayName : node.data.node.displayNameEn" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import item from "./item";
import { Addon } from "@antv/x6";
import { getGraph } from "../graph-common/graph";
export default {
  props: {
    lng: {
      type: String,
      default: ''
    }
  },
  components: { item },
  data() {
    return {
      groups: [],
      nodes: [],
      taskgroups:[],
      menuNodes: [],
      dnd: {},
      graph: {},
      collapse: false,
      language: '',
      keyword:'',
      filteredNodes: [], // 新增变量用于存储过滤后的节点列表
    };
  },
  watch: {
    lng: {
      handler(val) {
        this.language = val
      },
      immediate: true
    }
  },
  methods: {
    init(groups, nodes,taskgroups) {
      this.groups = groups;
      this.nodes = nodes;
      this.filteredNodes= nodes;
      this.taskgroups =taskgroups? taskgroups:[]
      this.graph = getGraph();
      const options = {
        target: this.graph,
      };
      this.dnd = new Addon.Dnd(options);
    },
    start(e, node) {
      const graph = this.graph;
      const ports = [];
      node.numInPorts = node.numInPorts !== undefined ? node.numInPorts : 1;
      node.numOutPorts = node.numOutPorts !== undefined ? node.numOutPorts : 1;
    // 根据节点的 numInPorts 属性创建对应数量的输入链接桩
  const colorList = ["#ff0000","#00ff00","#0000ff","#ff0000","#00ff00","#0000ff"]
    if(node.numInPorts>0){
    for (let i = 0; i < node.numInPorts; i++) {
    ports.push({
      group: "in",
      id: `in${i}`, // 为了确保链接桩的唯一性，可以添加一个唯一的 ID
      attrs: {
          circle: {
            stroke: colorList[i],
          },
        },
    });
  }
}
  // 根据节点的 numOutPorts 属性创建对应数量的输出链接桩
  if(node.numOutPorts>0){
  for (let i = 0; i < node.numOutPorts; i++) {
    ports.push({
      group: "out",
      id: `out${i}`, // 同样为了确保链接桩的唯一性，可以添加一个唯一的 ID
      attrs: {
          circle: {
            stroke: colorList[i],
          },
        },
    });
  }
  }
      const nodeModel = graph.createNode({
        shape: "rtNode",

        attrs: {
          label: {
            text: node.text,
          },
        },
        ports: ports, // 将动态生成的链接桩添加到节点配置中
        data: {
          ...node.data,
          icon: node.icon,
          text: node.text,
          color: node.color,
        },
      });
      this.dnd.start(nodeModel, e);
    },
    onCollapse() {
      this.collapse = !this.collapse;
      this.$emit('collapse', this.collapse)
    },
    changeLanguage() {
      if (this.language == 'zh-CN') {
        this.language = 'en-US'
      } else {
        this.language = 'zh-CN'
      }
      this.$emit('changeLanguage', this.language)
    },
    search(){
      if (!this.keyword.trim()) {
          this.groups.map(group => {
          group.expand = false;
        });
      // 如果 keyword 为空，则显示所有节点
      return this.filteredNodes = this.nodes.slice(0);
    }

    // 使用正则表达式匹配关键字（区分大小写）
    const regex = new RegExp(this.keyword, 'i');
    const matchedGroups = []; // 存储匹配到关键词的组别ID
    this.filteredNodes = this.nodes.filter((node) => {
      if (regex.test(node.data.node.displayName)) {
        matchedGroups.push(node.group); // 记录匹配到关键词的节点所在的组ID
        return true;
      }
      return false;
    });
     // 遍历groups，将匹配到的组别设置为展开状态
     this.groups.forEach((group) => {
      let isMatched = matchedGroups.includes(group.name);
      group.expand = isMatched;

      // 如果搜索关键词为空，则展开所有组别（可选，根据需求决定是否保留此项）
      if (!this.keyword.trim()) {
        group.expand = false;
      }
    });
    // 筛选出与关键字匹配的节点
   // this.filteredNodes = this.nodes.filter(node => regex.test(node.data.node.displayName));
 
    },
    clickGroup(group){
      this.$set(group, 'expand', !group.expand)
      this.$emit('changeGroup', group)
    },
  },
};
</script>

<style scoped lang="less">
.rt-x6-menu-head {
  position: relative;
  height: 36px;

  border-bottom: 1px solid #ececec;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;

  &:hover {
    background-color: rgba(0, 0, 0, 0.06);
  }
}

.rt-x6-menu {
  width: 220px;
  border-right: 1px solid #ececec;
  color: #303133;
  font-size: 12px;
}

.collapse {
  width: 40px;

  .group-page {
    display: none;
  }
}

.search {
  display: flex;
  justify-content: center;
}

.icon {
  font-size: 12px;
  margin: 0 8px;
}

.group-contaner {
  height: calc(100% - 68px);
  overflow: auto;

  &>div {
    &:first-child {
      border-top: none;
    }

    &:last-child {
      border-bottom: 1px solid #ececec;
    }
  }
}

.group-expand {
  border-bottom: 1px solid #ececec;
}

.group-page {
  border-top: 1px solid #ececec;
}
.taskgroup{
  padding: 8px 8px;
  cursor: pointer;
  background-color: #fbfbfb;
  font-weight: 600;
  color: #8231C9;

  &:hover {
    background-color: rgba(0, 0, 0, 0.06);
  }
}
.group-page:nth-child(2) .taskgroup{
  color: #ef672f;
}
.group {
  padding: 8px 8px;
  cursor: pointer;
  background-color: #fbfbfb;
  padding-left: 16px;
  &:hover {
    background-color: rgba(0, 0, 0, 0.06);
  }
}

.rt-input {
  width: 220px;
  font-size: 12px;
  display: block;
  margin: 4px;
  padding-left: 8px;
  height: 24px;
  color: #333;
  background: #fff;
  border: 1px solid #e9e9e9;
  border-radius: 2px;
  outline: 0;
}

.expand {
  transform: rotate(90deg);
  transition: transform 0.2s;
}

.lng {
  position: absolute;
  right: 16px;
  top: 10px;
  width: 16px !important;
  height: 16px !important;
}

/* 定义动画 */
@keyframes rotate {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 将动画应用到 SVG 图标上 */
.loadingsvg {
  animation: rotate 1s linear infinite; /* 使动画持续时间为1秒，线性变化，无限循环 */
  float: right;
}
</style>